import { UploadOutlined, UserOutlined, VideoCameraOutlined } from '@ant-design/icons';
import {Menu, MenuProps } from 'antd';
import React, { useState } from 'react';
import {useNavigate, useLocation} from 'react-router-dom';

type MenuItem = Required<MenuProps>['items'][number]
// 登录请求之后,就可以和item数组相匹配
const items: MenuItem[] = [
    {
      key:  '/page1',
      icon: <UploadOutlined />,
      label: '栏目1'
    },
    {
        key:  '/page2',
        icon: <VideoCameraOutlined />,
        label: '栏目2'
    },
    {
        key:  '/page3',
        icon: <UserOutlined />,
        label: '栏目3',
        children: [
            {
                key:  '/page3/page301',
                icon: <VideoCameraOutlined />,
                label: '栏目301'
            },
            {
                key:  '/page3/page302',
                icon: <VideoCameraOutlined />,
                label: '栏目302'
            }, 
        ]
    },
    {
        key:  '/page4',
        icon: <UserOutlined />,
        label: '栏目4',
        children: [
            {
                key:  '/page4/page401',
                icon: <VideoCameraOutlined />,
                label: '栏目401'
            },
            {
                key:  '/page4/page402',
                icon: <VideoCameraOutlined />,
                label: '栏目402'
            }, 
        ]
    },
]
function MainMenu() {
    const navigate = useNavigate();
    const currentRoute = useLocation();
    const menuClick = (e: { key: string }) => {  
      console.log('点击了', e.key);  
      // 点击跳转到对应路由  -- 编程式导航跳转 利用到一个hook
      navigate(e.key)  
    };
    let firstKey: string = '';
    // 用currentRoute.pathname 与items数组的每一项的children的key作对比,如果找到key, 就去拿他上一级的key
    //这个Key给到openKeys数组的元素,作为初始值
    function findKey (obj: {key: string}): boolean {
       return obj.key === currentRoute.pathname;
    }
    //找到展开那一项
    for(let i = 0; i < items.length; i++) {
        // 先判断有没有children
        const childLength = items[i]!['children'] && items[i]!['children'].length > 0 && items[i]!['children'].find(findKey);
        if (childLength) {
            firstKey = items[i]!.key as string;
            break
        }
    }
    // 设置展开项初始值
    const [openKeys, setOpenKeys] = useState([firstKey]);
    const handleChange = (keys: string[]) => {
      // 展开和回收某项菜单时执行这里的代码
      // key是一个数组,记录了当前哪一项是展开的(用key来记录)
      // 把数组修改为最后一项, 因为只有一项是展开的
      setOpenKeys([keys[keys.length - 1]])
    }
  return (
    <Menu
      theme="dark"
      mode="inline"
      // 菜单项数据
      items={items}
    //   defaultSelectedKeys 表示当前样式所在项的样式
      defaultSelectedKeys={[currentRoute.pathname]}
      onClick={menuClick}
      // 某项菜单展开和收起事件
      onOpenChange={handleChange}
      // 当前菜单展开项的key数组
      openKeys={openKeys}
  />
  )
}
export default MainMenu
